package org.ofbiz.framework.spring;

import org.ofbiz.base.container.Container;
import org.ofbiz.base.container.ContainerConfig;
import org.ofbiz.base.container.ContainerException;
import org.ofbiz.base.util.Debug;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringContainer implements Container {
    public static final String module = SpringContainer.class.getName();

    protected String configFileLocation = null;
//    protected ApplicationContext ctx = null;
    protected ClassPathXmlApplicationContext ctx = null;
    
    protected String configfile;
    protected String name;
    protected int port;
    
//	public void init(String[] args, String configFile)
//			throws ContainerException {
//		this.configFileLocation = configFile;
//	}

	public boolean start() throws ContainerException {
        // get the container config
        ContainerConfig.Container cfg = ContainerConfig.getContainer("spring-container", configFileLocation);
        System.out.println("configFileLocation = "+configFileLocation);
        System.out.println("cfg = "+cfg);
        // get the app-name
        ContainerConfig.Container.Property property = cfg.getProperty("configfile");
        System.out.println("property.value  = "+property.value );
        System.out.println("property  = "+property );
        if (property == null || property.value == null || property.value.length() == 0) {
            throw new ContainerException("Invalid configfile defined in container configuration");
        } else {
            this.configfile = property.value;
        }        
//        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/echo-provider.xml");
//        context.start();
        ctx = new ClassPathXmlApplicationContext(configfile); 
        ctx.start();
        if(ctx != null){
            Debug.logInfo("Started SpringFramework service on " + configfile, module);
    		return true;
        }else{
        	return false;
        }
	}

	public void stop() throws ContainerException {
		ctx = null;
        Debug.logInfo("Stoped SpringFramework service on " + configfile, module);
	}

	@Override
	public void init(String[] args, String name, String configFile) throws ContainerException {
		// TODO Auto-generated method stub
		System.out.println("configFile = "+configFile);
		System.out.println("name = "+name);
		System.out.println("args = "+args);
		this.configFileLocation = configFile;
		this.name =name;
		
	}

	@Override
	public String getName() {
		// TODO Auto-generated method stub
		return this.name;
	}

}
